<template>
  <div class="monitor-container">

    <el-button-group style="margin-bottom: 10px">
      <el-button
          icon="el-icon-refresh"
          size="default"
          :loading="loadingLock"
          @click="handleSync"
          round="true"
      >同步</el-button>
      <el-button
          icon="el-icon-download"
          size="default"
          @click="downloadMd"
          round="true"
      >保存</el-button>
    </el-button-group>

    <el-row :gutter="16">
      <!-- CPU -->
      <el-col :xs="24" :sm="12">
        <el-card shadow="hover" class="box-card">
          <div slot="header" class="card-header">
            <i class="el-icon-cpu"></i> CPU
          </div>
          <table class="simple-table">
            <tr><td>核心数</td><td>{{ cpu.cpuNum }}</td></tr>
            <tr><td>用户使用</td><td>{{ cpu.used }}%</td></tr>
            <tr><td>系统使用</td><td>{{ cpu.sys }}%</td></tr>
            <tr><td>当前空闲</td><td>{{ cpu.free }}%</td></tr>
          </table>
        </el-card>
      </el-col>

      <!-- 内存 -->
      <el-col :xs="24" :sm="12">
        <el-card shadow="hover" class="box-card">
          <div slot="header" class="card-header">
            <i class="el-icon-tickets"></i> 内存
          </div>
          <table class="simple-table">
            <thead>
            <tr><th></th><th>物理内存</th><th>JVM</th></tr>
            </thead>
            <tbody>
            <tr><td>总内存</td><td>{{ mem.total }} G</td><td>{{ jvm.total }} M</td></tr>
            <tr><td>已用</td><td>{{ mem.used }} G</td><td>{{ jvm.used }} M</td></tr>
            <tr><td>剩余</td><td>{{ mem.free }} G</td><td>{{ jvm.free }} M</td></tr>
            <tr>
              <td>使用率</td>
              <td :class="{danger: mem.usage > 80}">{{ mem.usage }}%</td>
              <td :class="{danger: jvm.usage > 80}">{{ jvm.usage }}%</td>
            </tr>
            </tbody>
          </table>
        </el-card>
      </el-col>

      <!-- 服务器信息 -->
      <el-col :span="24">
        <el-card shadow="hover" class="box-card">
          <div slot="header" class="card-header">
            <i class="el-icon-monitor"></i> 服务器信息
          </div>
          <table class="simple-table">
            <tr><td>服务器名</td><td>{{ sys.computerName }}</td><td>操作系统</td><td>{{ sys.osName }}</td></tr>
            <tr><td>服务器IP</td><td>{{ sys.computerIp }}</td><td>系统架构</td><td>{{ sys.osArch }}</td></tr>
          </table>
        </el-card>
      </el-col>

      <!-- JVM 信息 -->
      <el-col :span="24">
        <el-card shadow="hover" class="box-card">
          <div slot="header" class="card-header">
            <i class="el-icon-coffee-cup"></i> Java 虚拟机信息
          </div>
          <table class="simple-table">
            <tr><td>Java 名称</td><td>{{ jvm.name }}</td><td>Java 版本</td><td>{{ jvm.version }}</td></tr>
            <tr><td>启动时间</td><td>{{ jvm.startTime }}</td><td>运行时长</td><td>{{ jvm.runTime }}</td></tr>
            <tr><td>安装路径</td><td colspan="3">{{ jvm.home }}</td></tr>
            <tr><td>项目路径</td><td colspan="3">{{ sys.userDir }}</td></tr>
            <tr><td>运行参数</td><td colspan="3">{{ jvm.inputArgs || '-' }}</td></tr>
          </table>
        </el-card>
      </el-col>

      <!-- 磁盘状态 -->
      <el-col :span="24">
        <el-card shadow="hover" class="box-card">
          <div slot="header" class="card-header">
            <i class="el-icon-receiving"></i> 磁盘状态
          </div>
          <el-table :data="sysFiles" size="mini" style="width: 100%">
            <el-table-column prop="dirName" label="盘符路径" />
            <el-table-column prop="sysTypeName" label="文件系统" />
            <el-table-column prop="typeName" label="盘符类型" />
            <el-table-column prop="total" label="总大小" />
            <el-table-column prop="free" label="可用大小" />
            <el-table-column prop="used" label="已用大小" />
            <el-table-column label="使用率">
              <template slot-scope="s">
                <span :class="{danger: s.row.usage > 80}">{{ s.row.usage }}%</span>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import dayjs from 'dayjs'
import Cookies from 'js-cookie'
const COOKIE_KEY = 'monitor-server-info'
const COOKIE_EXPIRE = 1 / 24   // 单位：天

export default {
  name: 'Monitor',
  data() {
    return {
      cpu: {},
      mem: {},
      jvm: {},
      sys: {},
      sysFiles: [],
      loadingLock: false
    }
  },
  created() {
    this.loadAndRender()
  },
  methods: {
    /* 主逻辑：先读缓存 → 立即渲染 → 后台静默更新 */
    async loadAndRender() {
      const cached = Cookies.get(COOKIE_KEY)
      if (cached) {
        // 有缓存立即显示
        this.renderData(JSON.parse(cached))
        // 背后偷偷拿最新（用户感觉不到）
        await this.getServerInfo(true)
      } else {
        // 第一次
        await this.getServerInfo(false)
      }
    },

    /* 调接口：静默模式 silent=true 时不弹全屏loading */
    async getServerInfo(silent = false) {
      if (this.loadingLock) return
      this.loadingLock = true

      let loading = null
      if (!silent) {
        loading = this.$loading({
          lock: true,
          text: '正在加载服务器信息...',
          background: 'rgba(0,0,0,.5)'
        })
      }

      try {
        const res = await this.$request.get('/monitor/server')
        if (res.code !== '200') {
          if (!silent) this.$message.error(res.msg)
          return
        }
        // 渲染 + 写缓存
        this.renderData(res.data)
        Cookies.set(COOKIE_KEY, JSON.stringify(res.data), { expires: COOKIE_EXPIRE })
      } finally {
        if (loading) loading.close()
        this.loadingLock = false
      }
    },

    /* 统一渲染 */
    renderData(data) {
      this.cpu = data.cpu
      this.mem = data.mem
      this.jvm = data.jvm
      this.sys = data.sys
      this.sysFiles = data.sysFiles || []
    },

    /* 手动同步按钮事件 */
    handleSync() {
      this.getServerInfo(false)
    },
    downloadMd () {
      const d = JSON.parse(Cookies.get(COOKIE_KEY))          // 后端返回的完整对象
      console.log(d)
      const md = []

      /* 帮助：把任意对象转成 Markdown 表格 */
      const obj2table = (title, obj) => {
        if (!obj || typeof obj !== 'object') return ''
        const lines = ['### ' + title, '', '| 字段 | 值 |', '|------|---|']
        Object.entries(obj).forEach(([k, v]) => {
          // 基本类型直接显示，数组/对象转 JSON 字符串
          const val = typeof v === 'object' ? JSON.stringify(v) : String(v)
          lines.push(`| ${k} | ${val} |`)
        })
        lines.push('')
        return lines.join('\n')
      }

      /* 1. 基本信息 */
      md.push('## 服务器监控快照 - ' + dayjs().format('YYYY-MM-DD HH:mm'))
      md.push('')
      md.push(obj2table('CPU', d.cpu))
      md.push(obj2table('物理内存', d.mem))
      md.push(obj2table('JVM', d.jvm))
      md.push(obj2table('系统', d.sys))

      /* 2. 磁盘列表（多行） */
      md.push('### 磁盘分区')
      md.push('')
      md.push('| 盘符 | 文件系统 | 类型 | 总大小 | 已用 | 可用 | 使用率 |')
      md.push('|------|------------|------|--------|------|------|--------|')
      d.sysFiles.forEach(f =>
          md.push(`| ${f.dirName} | ${f.sysTypeName} | ${f.typeName} | ${f.total} | ${f.used} | ${f.free} | ${f.usage}% |`)
      )

      /* 3. 生成文件 */
      const blob = new Blob([md.join('\n')], { type: 'text/markdown;charset=utf-8' })
      const url = URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = '监控-' + dayjs().format('YYYY-MM-DD_HH-mm') + '.md'
      a.click()
      URL.revokeObjectURL(url)
    }
  }
}
</script>

<style scoped>
.monitor-container {
  padding: 16px;
  background: #f5f7fa;
}
.box-card {
  margin-bottom: 16px;
}
.card-header {
  font-weight: 600;
  display: flex;
  align-items: center;
}
.card-header i {
  margin-right: 6px;
}
.simple-table {
  width: 100%;
  border-collapse: collapse;
}
.simple-table td {
  padding: 8px 12px;
  border: 1px solid #ebeef5;
}
.simple-table td:first-child {
  background: #f5f7fa;
  width: 120px;
}
.danger {
  color: #f56c6c;
  font-weight: bold;
}
</style>